// 监听GAM自动广告展示
const listenGAMDisplay = (hostname: string) => {
	window.googletag = window.googletag || {cmd: []};
    window.googletag.cmd.push(function() {
		const { interstitial, topAnchor, bottomAnchor, rewarded, mainDisplay1, detailDisplay1, detailDisplay2, favoritesDisplay1, searchDisplay1 } = getGamConfig(hostname) || {}

        // slotRenderEnded 在广告渲染后自动回调
        window.googletag.pubads().addEventListener('slotRenderEnded', (event: any) => {
            const slotId = event.slot.getSlotElementId();
			const gamId = getAnalyticsConfig(hostname)?.gamId || ''
			// gam自动广告标识
			const autoGam = slotId.includes(gamId)
			if (autoGam) {
				if (event.isEmpty) {
					// 判断是什么广告展示失败
					if (slotId.includes(interstitial) && interstitial) {
						logEvent('GAM_Inter_AD_Show_Fail_Auto', { slot: interstitial })
					} 
					if (slotId.includes(topAnchor) && topAnchor) {
						logEvent('GAM_Anc_AD_Show_Fail_Auto', { slot: topAnchor })
					} 
					if (slotId.includes(bottomAnchor) && bottomAnchor) {
						logEvent('GAM_Anc_AD_Show_Fail_Auto', { slot: bottomAnchor })
					} 
					if (slotId.includes(rewarded) && rewarded) {
						logEvent('GAM_MRV_Show_Fail', { slot: rewarded })
					} 
					if (slotId.includes(mainDisplay1) && mainDisplay1) {
						logEvent('GAM_AD_Show_Fail', { slot: mainDisplay1 })
					} 
					if (slotId.includes(detailDisplay1) && detailDisplay1) {
						logEvent('GAM_AD_Show_Fail', { slot: detailDisplay1 })
					} 
					if (slotId.includes(detailDisplay2) && detailDisplay2) {
						logEvent('GAM_AD_Show_Fail', { slot: detailDisplay2 })
					} 
					if (slotId.includes(favoritesDisplay1) && favoritesDisplay1) {
						logEvent('GAM_AD_Show_Fail', { slot: favoritesDisplay1 })
					} 
					if (slotId.includes(searchDisplay1) && searchDisplay1) {
						logEvent('GAM_AD_Show_Fail', { slot: searchDisplay1 })
					}
				}
				
			}
        });

		window.googletag.pubads().addEventListener("rewardedSlotReady", (event: any) => {
			const btnPlay = document.getElementById("btnPlay");
			btnPlay?.addEventListener("click", () => {
				event.makeRewardedVisible();
			});
		});

		// 监听广告展示在页面中回调
		window.googletag.pubads().addEventListener("impressionViewable", (event: any) => {
			const { slot } = event
			const slotId = slot.getSlotElementId()
			if (slotId.includes(interstitial) && interstitial) {
				logEvent('GAM_Inter_AD_Show_Auto', { slot: interstitial })
			} 
			if (slotId.includes(topAnchor) && topAnchor) {
				logEvent('GAM_Anc_AD_Show_Auto', { slot: topAnchor })
			} 
			if (slotId.includes(bottomAnchor) && bottomAnchor) {
				logEvent('GAM_Anc_AD_Show_Auto', { slot: bottomAnchor })
			} 
			if (slotId.includes(rewarded) && rewarded) {
				logEvent('GAM_MRV_Show', { slot: rewarded })
			} 
			if (slotId.includes(mainDisplay1) && mainDisplay1) {
				logEvent('GAM_AD_Show', { slot: mainDisplay1 })
			} 
			if (slotId.includes(detailDisplay1) && detailDisplay1) {
				logEvent('GAM_AD_Show', { slot: detailDisplay1 })
			} 
			if (slotId.includes(detailDisplay2) && detailDisplay2) {
				logEvent('GAM_AD_Show', { slot: detailDisplay2 })
			} 
			if (slotId.includes(favoritesDisplay1) && favoritesDisplay1) {
				logEvent('GAM_AD_Show', { slot: favoritesDisplay1 })
			} 
			if (slotId.includes(searchDisplay1) && searchDisplay1) {
				logEvent('GAM_AD_Show', { slot: searchDisplay1 })
			}
		});
    });
}

// 监听AdSense自动广告展示
const listenAdSenseDisplay = () => {
    let observe = null; //监听器
    const AdsContent = document.querySelectorAll('.adsbygoogle-noablate');
    if (!AdsContent || AdsContent.length === 0) return;
    const Ads = AdsContent[0];
    if (!Ads) return;

    // 监听配置
    const config = {
        subtree: true,
        attributeFilter: ["data-ad-status"],
    }

    // 监听回调
    const callback = (mutationsList: any, observer: any) => {
        const target = mutationsList[0].target;
        const adStatus = target.getAttribute("data-ad-status");
		const interstitialLoaded = target.getAttribute("data-vignette-loaded");
		const anchorLoaded = target.getAttribute("data-anchor-status");
        if (adStatus == "filled") {
			if (interstitialLoaded) {
				console.log('AdSense自动插页广告展示成功', target);
			}
			if (anchorLoaded) {
				console.log('AdSense自动锚定广告展示成功', target);
			}
            observer.disconnect();
        } else if (adStatus == "unfilled") {
            if (interstitialLoaded) {
				console.log('AdSense自动插页广告展示失败', target);
			}
			if (anchorLoaded) {
				console.log('AdSense自动锚定广告展示失败', target);
			}
            observer.disconnect();
        }
    };

    // 创建监听
    observe = new MutationObserver(callback);
    observe.observe(Ads, config);
}

// 加载GAM自动广告
const loadAutoGam = (hostname: string, queryParams: any) => {
	const channel = queryParams.Channel || ''
	let interstitialSlot: any, topAnchorSlot: any, bottomAnchorSlot: any, rewardedSlot: any

	const interstitialPath = getGamAutoAdSlot('interstitial', hostname) || ''
	const topAnchorPath = getGamAutoAdSlot('topAnchor', hostname) || ''
	const bottomAnchorPath = getGamAutoAdSlot('bottomAnchor', hostname) || ''
	const rewardedPath = getGamAutoAdSlot('rewarded', hostname) || ''
	

	window.googletag = window.googletag || {cmd: []};
	window.googletag.cmd.push(() => {
		if (interstitialPath) interstitialSlot = window.googletag.defineOutOfPageSlot( interstitialPath, window.googletag.enums.OutOfPageFormat.INTERSTITIAL);
		if (topAnchorPath) topAnchorSlot = window.googletag.defineOutOfPageSlot( topAnchorPath, window.googletag.enums.OutOfPageFormat.TOP_ANCHOR);
		if (bottomAnchorPath) bottomAnchorSlot = window.googletag.defineOutOfPageSlot( bottomAnchorPath, window.googletag.enums.OutOfPageFormat.BOTTOM_ANCHOR);
		if (rewardedPath) rewardedSlot = window.googletag.defineOutOfPageSlot( rewardedPath, window.googletag.enums.OutOfPageFormat.REWARDED);
		if (interstitialSlot) interstitialSlot.addService(window.googletag.pubads()).setConfig({ targeting: { test: "anchor"}});
		if (topAnchorSlot) topAnchorSlot.addService(window.googletag.pubads()).setConfig({ targeting: { test: "anchor"}});
		if (bottomAnchorSlot) bottomAnchorSlot.addService(window.googletag.pubads()).setConfig({ targeting: { test: "anchor"}});
		if (rewardedSlot) rewardedSlot.addService(window.googletag.pubads()).setConfig({ targeting: { test: "anchor"}});
		window.googletag.pubads().setTargeting('afc_channel', channel);
		window.googletag.pubads().enableSingleRequest();
		window.googletag.pubads().collapseEmptyDivs();
		window.googletag.enableServices();
		interstitialSlot && window.googletag.display(interstitialSlot)
		topAnchorSlot && window.googletag.display(topAnchorSlot)
		bottomAnchorSlot && window.googletag.display(bottomAnchorSlot)
		rewardedSlot && window.googletag.display(rewardedSlot)
	});
	// 等待 Google Ad Manager 完全就绪
}

// 处理广告展示上报
const trackAdDisplay = (hostname: string) => {
    listenGAMDisplay(hostname)
    listenAdSenseDisplay()
}

// 处理广告点击上报
const trackAdClick = () => {
	const activeElement = document.activeElement;
    if (!activeElement) return;
	
	const hostname = useHostname()
	const InterAdElement = activeElement.closest('[data-vignette-loaded]')
	const AnchorAdElement = activeElement.closest('[data-anchor-shown]')
	const ManualAdElement = activeElement.closest('[data-ad-manager]')
	const MRVAdElement = activeElement.closest('[id*="_MRV"]') || activeElement.closest('[id*="web_example"]')

	const { gamId } = getAnalyticsConfig(hostname) || {}
	const GAMAdElement = activeElement.closest(`[id*="${gamId}"]`)
	console.log('GAMAdElement', GAMAdElement);
	// 广告id为gpt_unit_/6355419/Travel/Europe/France/Paris_1
	// 则slot为Travel/Europe/France/Paris_1
	let slotAll = ''
	if (InterAdElement) {
		const slot = InterAdElement.id.replace(/^gpt_unit_\/\d+\//, '')
		logEvent('GAM_Inter_Click_Auto', {
			slot: slot
		})
		slotAll = slot
	}
	if (AnchorAdElement) {
		const slot = AnchorAdElement.id.replace(/^gpt_unit_\/\d+\//, '')
		logEvent('GAM_Anc_Click_Auto', {
			slot: slot
		})
		slotAll = slot
	}
	if (ManualAdElement) {
		const slot = ManualAdElement.id.replace(/^gpt_unit_\/\d+\//, '')
		logEvent('GAM_AD_Click', {
			slot: ManualAdElement.id.replace(/^gpt_unit_\/\d+\//, '')
		})
		slotAll = slot
	}
	if (MRVAdElement) {
		const slot = MRVAdElement.id.replace(/^gpt_unit_\/\d+\//, '')
		logEvent('GAM_MRV_Click', {
			slot: slot
		})
		slotAll = slot
	}

	// 只统计GAM广告
	if (GAMAdElement) {
		logEvent('GAM_AD_Click_All', { slot: slotAll })
	}
	// 上报所有广告点击GAM+AFC
	logEvent('Sum_AD_Click_All', { slot: slotAll })
	
	// adsense手动广告点击上报
	// adsense自动广告点击上报
}

// 用户是否点击插页广告关闭按钮
const interClose = ref(false)
//当前页面是否因为点击iframe失去焦点
const isBlurTriggered = ref(false);

const windowMessage = (hostname: string) => {
    interClose.value = false;
	// 监听广告iframe postMessage通知来判断广告关闭
	window.addEventListener('message', (event) => {
		// let adSenseDomain = 'https://googleads.g.doubleclick.net';
		if(event.data && typeof event.data === 'string' && event.data.includes('adClosed')){
			interClose.value = true
			// 获取当前插页广告的slot
			const { interstitial } = getGamConfig(hostname) || {}
			logEvent('GAM_Inter_Close_Click', { slot: interstitial })
		}
	});
}

// 页面失去焦点
const windowBlur = () => {
	window.addEventListener("blur", () => {
		let ACTIVELEMENT = document.activeElement;
		if ('IFRAME' === (null === ACTIVELEMENT || undefined === ACTIVELEMENT ? undefined : ACTIVELEMENT.nodeName)) {
			isBlurTriggered.value = true;
			setTimeout(() => {
				isBlurTriggered.value = false;
				window.focus(); // 延时foucs，因为广告跳转前会获取activeElement，太早focus会导致跳转前activeElement是body
			}, 300);
		}
    })
}    

// 页面展示隐藏
const windowVisible = () => {
	window.addEventListener("visibilitychange", () => {
		if (document.visibilityState == "hidden" && isBlurTriggered.value) {
			trackAdClick();
		} else if (document.visibilityState == "visible") {
			setTimeout(() => window.focus(), 0);
		}
	});
};

// 关闭页面之前
const windowBeforeUnload = () => {
	window.addEventListener("beforeunload", () => {
		let ACTIVELEMENT = document.activeElement;
		if ('IFRAME' === (null === ACTIVELEMENT || undefined === ACTIVELEMENT ? undefined : ACTIVELEMENT.nodeName)) {
			if (interClose.value) {
				// 页面内跳转，非广告点击
			} else {
				trackAdClick();
			}
		};
	});
};

// 重置谷歌锚定广告设置的body内边距
const resetBodyPadding = () => {
    // 使用MutationObserver监听body的style属性变化
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                const body = document.body;
                if (body.style.padding && body.style.padding !== '0px') {
                    // 重置padding
                    body.style.padding = '0';
                    console.log('已重置谷歌广告设置的body内边距');
                }
            }
        });
    });

    // 开始监听body的style属性变化
    observer.observe(document.body, {
        attributes: true,
        attributeFilter: ['style']
    });

    // 立即检查并重置
    if (document.body.style.padding && document.body.style.padding !== '0px') {
        document.body.style.padding = '0';
    }

    return observer;
};

export const handleAdInteraction = (hostname: string, queryParams: any) => {
	loadAutoGam(hostname, queryParams)
    windowMessage(hostname);
    windowBlur();
    windowVisible();
    windowBeforeUnload();
	trackAdDisplay(hostname)
	
	// 重置body内边距
	// resetBodyPadding();
}